﻿using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace NativeCode.Core.Extensions
{
	public static class StringExtensions
	{
		public static bool IsNullOrEmpty(this string source)
		{
			return string.IsNullOrEmpty(source);
		}

		public static string ToDisplayText(this string source)
		{
			return string.Join(" ", SplitCamelCase(source));
		}

		public static string[] SplitCamelCaseRegex(this string source)
		{
			return Regex.Replace(source, "([A-Z])", " $1", RegexOptions.Compiled).Trim().Split(' ');
		}

		public static string Times(this string source, int times)
		{
			string results = string.Empty;

			for (int i=1; i < times; i++)
			{
				results += source;
			}

			return results;
		}

		#region Code stolen from somewhere, I don't remember...

		public static string[] SplitCamelCase(this string source)
		{
			if (string.IsNullOrEmpty(source))
			{
				return new string[] {}; //Return empty array.
			}

			StringCollection words = new StringCollection();
			int wordStartIndex = 0;

			char[] letters = source.ToCharArray();
			char previousChar = char.MinValue;

			// Skip the first letter. we don't care what case it is.
			for (int i = 1; i < letters.Length; i++)
			{
				if (char.IsUpper(letters[i]) && !char.IsWhiteSpace(previousChar))
				{
					//Grab everything before the current character.
					words.Add(new string(letters, wordStartIndex, i - wordStartIndex));
					wordStartIndex = i;
				}
				previousChar = letters[i];
			}

			//We need to have the last word.
			words.Add(new string(letters, wordStartIndex, letters.Length - wordStartIndex));
			string[] wordArray = new string[words.Count];

			words.CopyTo(wordArray, 0);
			return wordArray;
		}

		#endregion
	}
}